package edu.ntu.im.p2ptrade.msg.handle;

import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

import net.jxta.endpoint.Message;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.RegularExpression;

import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.Util;
import edu.ntu.im.p2ptrade.entity.Item;
import edu.ntu.im.p2ptrade.entity.ItemRepository;
import edu.ntu.im.p2ptrade.msg.AuthenticatedMessageWrapper;
import edu.ntu.im.p2ptrade.msg.PMessage;
import edu.ntu.im.p2ptrade.msg.SearchItemQuery;
import edu.ntu.im.p2ptrade.msg.SearchResult;

public class SearchItemQueryHandle implements PMessageHandle{

	public void handle(Message msg) {
		String search = msg.getMessageElement(P2PTrade.getInstance().getAppName(), SearchItemQuery.QUERY).toString();
		String from = msg.getMessageElement(P2PTrade.getInstance().getAppName(), PMessage.PEER).toString();
		List<Item> items = ItemRepository.getInstance().getItems();
		List<Item> result = new LinkedList<Item>();
		StringTokenizer st = new StringTokenizer(search, "*");
		String qterm = st.nextToken();
		System.out.println("qterm:"+qterm);
		for (Item item: items){
			String name = item.getName();
			String memo = item.getMemo();
			if (name.indexOf(qterm)>=0 || memo.indexOf(qterm)>=0){
				result.add(item);
			}
		}
		System.out.println("search term:"+search);
		PMessage sr = new AuthenticatedMessageWrapper(new SearchResult(result, search));
		try {
			Util.transdferMessageToPeer(sr.getMessageToTransfer(), from);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
